package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw=new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,currentId).orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressService.list(lqw));
    }
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        addressService.save(addressBook);
        return R.success("保存成功");
    }
    //设置默认地址
    @PutMapping("/default")
    public R<AddressBook> update(@RequestBody AddressBook addressBook){
        //先将地址列表中所有is_default字段重置为0
        Long currentId = BaseContext.getCurrentId();
        LambdaUpdateWrapper<AddressBook> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId,currentId);
        //将所有地址的默认状态设置为0
        wrapper.set(AddressBook::getIsDefault,0);
        //将当前地址默认状态设置为1
        addressService.update(wrapper);
        addressBook.setIsDefault(1);
        addressService.updateById(addressBook);
        return R.success(addressBook);
    }
    @GetMapping("/default")
    public R<AddressBook> get(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw=new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,currentId);
        lqw.eq(AddressBook::getIsDefault,1);
        AddressBook defaultAddress = addressService.getOne(lqw);
        return R.success(defaultAddress);
    }

}
